/********************************************************************************
 * Project Name		[JavaEE_JDBC]
 * File Name     	[SQLInjection.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package other;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import utils.jdbc.JdbcUtils;

/**
 * 演示SQL注入
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class SQLInjection {

	private Connection connection;
	private Statement statement;
	private ResultSet resultSet;

	@Before
	public void init() throws Exception {
		connection = JdbcUtils.getInstance().getConnection();
	}

	/**
	 * 测试正常的查询
	 * 
	 * @throws Exception
	 */
	@Test
	public void testNormalQuery() throws Exception {
		// 正常查询, 查到一条对应记录
		queryByName("Sean"); //
	}

	/**
	 * 演示SQL注入
	 * 
	 * @throws Exception
	 */
	@Test
	public void testSQLInjection() throws Exception {
		// SQL注入, 查到所有记录
		queryByName("' OR 1 = 1 OR '");
	}

	/**
	 * 根据用户名查找用户
	 * 
	 * @param username
	 * @throws Exception
	 */
	private void queryByName(String username) throws Exception {
		String sql = "SELECT * FROM User WHERE username = '" + username + "'";
		statement = connection.createStatement();
		resultSet = statement.executeQuery(sql);
		System.out.println(sql);
		while (resultSet.next()) {
			System.out.println(resultSet.getString("username"));
		}
	}

	@After
	public void destroy() {
		JdbcUtils.getInstance().close(resultSet, statement, connection);
	}
}
